﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;

using MINERP.ComControls;
using MINERP.BLL.GroupSample;
using MINERP.MODEL.GroupSample;
using MINERP.SharpZipLib;
using System.IO;
using MINERP.MODEL.FoundationModel;


namespace MINERP.GroupSample
{
    public partial class FrmMain : FrmParent
    {
        private GroupSampleBLL _bll = new GroupSampleBLL();

        public delegate void SetBarMaxNumHander(int num);
        public static string rebackRemark;

        public FrmMain()
        {
            InitializeComponent();
        }
        List<Tb_Tech_Info> OperTech = new List<Tb_Tech_Info>();
        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                List<Tb_Tech_Info> listTech = _bll.GetAllTech();
                foreach (Tb_Tech_Info tech in listTech)
                {
                    if (operates.Keys.Contains(tech.TechId)!=null)
                    {
                        OperTech.Add(tech);
                    }
                }
                BindTaskInfoList(OperTech);
                if(!string.IsNullOrEmpty(Properties.Settings.Default.SavePath))
                {
                    folderBrowserDialog1.SelectedPath = Properties.Settings.Default.SavePath;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void BindTaskInfoList()
        {
            List<TaskInfo> taskInfoList = _bll.GetListTask(userId, chkIsAllTask.Checked);
            gcTaskInfo.DataSource = taskInfoList;
            gcTaskInfo.RefreshDataSource();
        }
        private void BindTaskInfoList(List<Tb_Tech_Info>  listTech)
        {
            List<TaskInfo> taskInfoList = _bll.GetListTask(userId, chkIsAllTask.Checked, listTech);
            gcTaskInfo.DataSource = taskInfoList;
            gcTaskInfo.RefreshDataSource();
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            BindTaskInfoList(OperTech);
        }

        /// <summary>
        /// 生成小样
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMakeSmallPic_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("确定生成选中产品的小样？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                try
                {
                    btnExport.Enabled = false;//生成小样时不能导出小样
                    if (!bwMakeSmallPic.IsBusy)
                    {
                        bwMakeSmallPic.RunWorkerAsync();

                    }
                    else
                    {
                        MessageBox.Show("正在生成小样,请稍等...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                finally
                {
                    btnExport.Enabled = true;
                }
            }

        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void bwMakeSmallPic_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker work = sender as BackgroundWorker;
                MakeSmallPic(work);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void MakeSmallPic(BackgroundWorker work)
        {
            List<TaskInfo> taskList = new List<TaskInfo>();
            List<int> handles = gvTaskInfo.GetSelectedRows().ToList();
            foreach (var item in handles)
            {
                taskList.Add((TaskInfo)gvTaskInfo.GetRow(item));
            }
            foreach (var item in taskList)
            {
                SetBarMaxNum(item.PhotoList.Count);
                _bll.MakSmallPic(item, work);
            }
        }

        private void bwMakeSmallPic_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 0;
        }

        private void bwMakeSmallPic_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void SetBarMaxNum(int num)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new SetBarMaxNumHander(SetBarMaxNum), new object[] { num });
            }
            else
            {
                progressBar1.Maximum = num;
            }
        }

        /// <summary>
        /// 标记已发小样
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendSmallPic_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("确定标记选中产品为“已发样”状态？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    List<TaskInfo> taskList = new List<TaskInfo>();
                    List<int> handles = gvTaskInfo.GetSelectedRows().ToList();
                    foreach (var item in handles)
                    {
                        taskList.Add((TaskInfo)gvTaskInfo.GetRow(item));
                    }
                    _bll.SendSmallPic(taskList);

                    BindTaskInfoList(OperTech);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void gvTaskInfo_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView gv = sender as GridView;
            TaskInfo ti = gv.GetRow(e.RowHandle) as TaskInfo;

            if (ti.SmallPicStatus == "已发样")
            {
                e.Appearance.BackColor = Color.GreenYellow;
            }
        }
        /// <summary>
        /// 退回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRetreat_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("确定退回选中产品到设计岗位？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    string msg = "";
                    TaskInfo ti = gvTaskInfo.GetFocusedRow() as TaskInfo;
                    FrmRebackRemark frm = new FrmRebackRemark();
                    frm.ShowDialog();
                    bool ret = _bll.ReBackTask(ti, rebackRemark, out msg);
                    if (ret)
                    {
                        MessageBox.Show("产品：" + ti.OrderProductId + "已退回到设计岗位！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        BindTaskInfoList();
                    }
                    else
                    {
                        MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                rebackRemark = "";
            }

        }

        /// <summary>
        /// 完成看样
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnComplete_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("确定完成选中产品的看样？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    int[] listArraySelectedID = gvTaskInfo.GetSelectedRows();
                    foreach (int rowid in listArraySelectedID)
                    {
                        TaskInfo ti = gvTaskInfo.GetRow(rowid) as TaskInfo;
                        _bll.CompleteWork(ti.TechId, userId, ti.OrderProductId);
                    }
                    BindTaskInfoList(OperTech);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                btnMakeSmallPic.Enabled = false;//导出小样时不能生成小样
                
                if (!bwExport.IsBusy)
                {
                    if (DialogResult.OK == folderBrowserDialog1.ShowDialog())
                    {
                        string dirPath = folderBrowserDialog1.SelectedPath;
                        Properties.Settings.Default.SavePath = dirPath;
                        Properties.Settings.Default.Save();
                        bwExport.RunWorkerAsync(dirPath);
                    }
                }
                else
                {
                    MessageBox.Show("正在导出中...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                btnMakeSmallPic.Enabled = true;
            }

        }

        private void Export(string dirPath)
        {
            try
            {
                List<int> handles = gvTaskInfo.GetSelectedRows().ToList();
                if (handles.Count > 0)
                {
                    SetBarMaxNum(handles.Count);
                    int index = 0;
                    foreach (var item in handles)
                    {
                        TaskInfo ti = (TaskInfo)gvTaskInfo.GetRow(item);
                        string sourcePath = ti.OrderPath + "\\看样";
                        string destPath = dirPath + "\\" + ti.OrderProductId + "_" + ti.ShopName + "_" + ti.CtmName + "_" + ti.OrderProductName + ".zip";
                        ZipClass.ZipFolder(destPath, sourcePath);
                        index++;
                        bwExport.ReportProgress(index);
                    }
                    MessageBox.Show("导出完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("请选择要导出小样的产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("还有产品未生成小样！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
        private void ExportBag(string dirPath)
        {
            try
            {
                List<int> handles = gvTaskInfo.GetSelectedRows().ToList();
                if (handles.Count > 0)
                {
                    SetBarMaxNum(handles.Count);
                    int index = 0;
                    string RootForder = dirPath + "\\" + DateTime.Now.Date.ToString("yyyyMMdd");
                    TaskInfo tiN = (TaskInfo)gvTaskInfo.GetRow(handles.First());
                    RootForder += "\\"+tiN.ShopName+"\\" + tiN.orderBagID + "_" + tiN.CtmName;//客户文件夹
                    if (!Directory.Exists(RootForder))
                    {
                        Directory.CreateDirectory(RootForder);
                    }
                    foreach (var item in handles)
                    {
                        TaskInfo ti = (TaskInfo)gvTaskInfo.GetRow(item);
                        string sourcePath = ti.OrderPath + "\\看样";

                        string destPath = RootForder+"\\" + ti.OrderProductId + "_" + ti.OrderProductName + ".zip";
                        ZipClass.ZipFolder(destPath, sourcePath);
                        index++;
                        bgwExportBag.ReportProgress(index);
                    }
                    ZipClass.ZipFolder( RootForder + ".zip",RootForder);
                    Directory.Delete(RootForder, true);

                    MessageBox.Show("导出完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("请选择要导出小样的产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("还有产品未生成小样！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
        private void bwExport_DoWork(object sender, DoWorkEventArgs e)
        {
            Export(e.Argument.ToString());
        }

        private void bwExport_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void bwExport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 0;

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton_Click(object sender, EventArgs e)
        {
            List<int> rowIdList = gvTaskInfo.GetSelectedRows().ToList();
            List<TaskInfo> listTask = new List<TaskInfo>();
            foreach (int rowID in rowIdList)
            {
                TaskInfo ti = (TaskInfo)gvTaskInfo.GetRow(rowID);
                listTask.Add(ti);
            }
            var listGroup = listTask.GroupBy(g => g.orderBagID);
            if (listGroup.Count() > 1)
            {
                MessageBox.Show("不同订单不能合并导出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            try
            {
                toolStripButtonBagExport.Enabled = false;//导出小样时不能生成小样
                if (!bgwExportBag.IsBusy)
                {
                    if (DialogResult.OK == folderBrowserDialog1.ShowDialog())
                    {
                        string dirPath = folderBrowserDialog1.SelectedPath;
                        Properties.Settings.Default.SavePath = dirPath;
                        Properties.Settings.Default.Save();
                        bgwExportBag.RunWorkerAsync(dirPath);
                    }
                }
                else
                {
                    MessageBox.Show("正在导出中...", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                toolStripButtonBagExport.Enabled = true;
            }

        }

        private void bgwExportBag_DoWork(object sender, DoWorkEventArgs e)
        {
            ExportBag((string)e.Argument);
        }

        private void bgwExportBag_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void bgwExportBag_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

    }
}
